package udp

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"time"

	"gitee.com/tsingeye/FreeEhome/config"
	"gitee.com/tsingeye/FreeEhome/tools"
	"gitee.com/tsingeye/FreeEhome/tools/logs"
)

var (
	udpGateway *gatewayForUDP //UDP网关
	xmlConfig  XMLConfigInfo  //解析配置文件中的XML文件
)

func init() {
	os.Chdir(tools.GetAbsPath())
	file, err := os.Open("./conf/config.xml")
	//file, err := os.Open("E:\\Go\\src\\gitee.com\\tsingeye\\FreeEhome\\conf\\config.xml")
	if err != nil {
		logs.PanicLogger.Panicln(fmt.Sprintf("udp.init() ---> os.Open('./conf/config.xml') error:%s", err))
	}

	defer file.Close()
	fileData, err := ioutil.ReadAll(file)
	if err != nil {
		logs.PanicLogger.Panicln(fmt.Sprintf("udp.init() ---> ioutil.ReadAll() error:%s", err))
	}

	if err := xml.Unmarshal(fileData, &xmlConfig); err != nil {
		logs.PanicLogger.Panicln(fmt.Sprintf("udp.init() ---> fileData=%s, xml.Unmarshal() error:%s", fileData, err))
	}
}

//启动UDP server服务器
func ListenUDPServer() {
	//创建udp地址
	udpAddr, err := net.ResolveUDPAddr("udp", config.EHomeUDPAddr)
	if err != nil {
		fmt.Printf("%s ListenUDPServer() ---> net.ResolveUDPAddr() error:%s\n", time.Now().Format(config.TimeLayout), err)
		logs.PanicLogger.Panicln(fmt.Sprintf("ListenUDPServer() ---> net.ResolveUDPAddr() error:%s", err))
	}

	//监听udp地址
	udpConn, err := net.ListenUDP("udp", udpAddr)
	if err != nil {
		fmt.Printf("%s ListenUDPServer() ---> net.ListenUDP() error:%s\n", time.Now().Format(config.TimeLayout), err)
		logs.PanicLogger.Panicln(fmt.Sprintf("ListenUDPServer() ---> net.ListenUDP() error:%s", err))
	}

	fmt.Printf("%s ListenUDPServer() ---> start EHome's udpServer successful!!!\n", time.Now().Format(config.TimeLayout))
	logs.BeeLogger.Emergency("ListenUDPServer() ---> start EHome's udpServer successful!!!")

	//初始化一个UDP网关
	udpGateway = NewUDPGateway(udpConn)
	udpGateway.readFromUDP()
}
